﻿using System;
using System.Net.Mail;
using System.Text;
using System.Web;
using System.Web.UI;
using GateKeeper;

public partial class GateKeeper_AccessDenied : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        btnSend.Click += new EventHandler(btnSend_Click);
        if (!Page.IsPostBack)
        {
            txtName.Text = Request.QueryString["name"];
            txtEmail.Text = Request.QueryString["email"];

            SetFocus();
        }
    }

    private void SetFocus()
    {
        if (string.IsNullOrEmpty(Request.QueryString["name"]) && txtName.Text == string.Empty)
        { txtName.Focus(); }
        else if (string.IsNullOrEmpty(Request.QueryString["email"]) && txtEmail.Text == string.Empty)
        { txtEmail.Focus(); }
        else
        { txtMessage.Focus(); }
    }

    private void btnSend_Click(object sender, EventArgs e)
    {
        if (Page.IsValid && GateKeeperModule.config.NotifyAdmin)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("<div>");
            sb.AppendLine("<h2 style=\"color: navy; padding: 15px 0; \">GateKeeper Dispute Request</h2>");
            sb.AppendLine(string.Format("<p>{0}</p>", HttpUtility.HtmlEncode(txtMessage.Text)));
            sb.AppendLine(string.Format("<p style=\"border-top: 1px solid #999999\">IP Address: {0}<br />", HttpContext.Current.Request.UserHostAddress));
            sb.AppendLine(string.Format("UserAgent: {0}<br />", HttpUtility.HtmlEncode(HttpContext.Current.Request.UserAgent)));
            sb.AppendLine(string.Format("Referrer: {0}</p>", HttpUtility.HtmlEncode(HttpContext.Current.Request.UrlReferrer.AbsoluteUri)));
            sb.AppendLine("</div>");

            MailMessage mail = new MailMessage();
            mail.From = new MailAddress(GateKeeperModule.config.SmtpEmailAddress);
            mail.To.Add(GateKeeperModule.config.SmtpEmailAddress);

            mail.Subject = "GateKeeper Dispute Request Submitted";
            mail.Body = sb.ToString();

            try
            {
                GateKeeperModule.log.Debug("Sending dispute message");
                GateKeeper.Smtp.SendMailMessageAsync(mail);
                return;
            }
            catch (Exception ex)
            {
                GateKeeperModule.log.WarnFormat("Dispute Contact Form : [{0}]", ex.Message);
                GateKeeperModule.log.Error(ex.StackTrace);
                return;
            }
            finally
            {
                divForm.Visible = !divForm.Visible;
                divResult.Visible = !divResult.Visible;
            }
        }
    }
}
